<html>

<head>
</head>

<body>
  <div>
  </div>
</body>
<script>

  // 交集
  function jiaoji(arr1, arr2, key) {
    let tmpArr = [];
    for (let i = 0, len = arr1.length; i < len; i++) {
      tmpArr.push(arr1[i][key])
    }
    let result = arr2.filter(function (item) {
      return tmpArr.indexOf(item[key]) !== -1
    })
    return result
  }
  let arr1 = [{ id: 1, name: 'apple' }, { id: 2, name: 'banana' }, { id: 3, name: 'cat' }];
  let arr2 = [{ id: 1, name: 'apple' }, { id: 2, name: 'banana' }, { id: 3, name: 'cat' }, { id: 4, name: 'dog' }, { id: 5, name: 'egg' }];
  console.log('交集', jiaoji(arr1, arr2, 'id')); // [{ id: 1, name: 'apple' }, { id: 2, name: 'banana' }, { id: 3, name: 'cat' }]




  // 并集
  function bingji(arr1, arr2, key){
    let arr3 = arr1.concat(arr2);
    let result = [];
    let obj = [];
    result = arr3.reduce(function(prev, cur, index, arr){
        obj[cur[key]] ? '' : obj[cur[key]] = true && prev.push(cur);
        return prev;
    }, []);
    return result
  }
  let arr3 = [{id:1,name:'apple'},{id:2,name:'banana'},{id:3,name:'cat'}];
  let arr4 = [{id:1,name:'apple'},{id:2,name:'banana'},{id:3,name:'cat'},{id:4,name:'dog'},{id:5,name:'egg'}];
  console.log('并集', bingji(arr3, arr4, 'id')); // [{id:1,name:'apple'},{id:2,name:'banana'},{id:3,name:'cat'},{id:4,name:'dog'},{id:5,name:'egg'}]


  // 差集
  function chaji(arr1, arr2, key) {
    let arr1Id = arr1.map(e => e[key]);
    let arr2Id = arr2.map(e => e[key]);
    let arr3 = arr1.concat(arr2);
    let result = arr3.filter(function (v) {
      return arr1Id.indexOf(v[key]) === -1 || (arr2Id.indexOf(v[key]) === -1)
    })
    return result
  }
  let arr5 = [{ name: 'name3', id: 3 }];
  let arr6 = [{ name: 'name1', id: 3 }, { name: 'name4', id: 3 }, { name: 'name5', id: 3 }, {name: '11', id: 2}];
  console.log('差集1', chaji(arr5, arr6, 'id')); // []
  let arr7 = [{ name: 'name3', id: 3 }];
  let arr8 = [{ name: 'name1', id: 3 }, { name: 'name4', id: 3 }, { name: 'name5', id: 3 }, {name: '11', id: 2}];
  console.log('差集2', chaji(arr7, arr8, 'id')); // [{name: '11', id: 2}]



  
//去重
// let arr = [{name:'name1',id:1},{name:'name2',id:2},{name:'name3',id:3},{name:'name1',id:1},{name:'name4',id:4},{name:'name5',id:5}];
// var obj = [];
// let result = arr.reduce(function(prev, cur, index, arr) {
//     console.log(prev, cur);
//     obj[cur.id] ? '' : obj[cur.id] = true && prev.push(cur);
//     return prev;
// }, []);
</script>

</html>